import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import ButtonModel from 'base/models/ButtonModel';
import ButtonWidget from 'widgets/ButtonWidget';
import SelectWidget from 'widgets/SelectWidget';
import DateWidget from 'widgets/DateWidget';
import InputWidget from 'widgets/InputWidget';
import CombinationView from './CombinationView';

const template = require('./templates/CommonCriteriaView.mustache');


const CommonCriteriaView = Mn.View.extend({
    template: template,
    tagName: 'li',
    regions: {
        combination: ".combination",
        selector: ".form-group.selector",
        method: '.form-group.method',
        search1: '.form-group.search1',
        search2: '.form-group.search2',
        deleteButton: {el: '.delbutton-container', replaceElement: true},
        addButton: '.addbutton-container',
    },
    ui: {form: 'form'},
    events: {
        'submit @ui.form': "onFormSubmit"
    },
    childViewEvents: {
        'finish': 'onFieldSelect',
        'action:clicked': 'onActionClicked',
    },
    childViewTriggers: {},
    modelEvents: {
        'saved': 'onModelSaved',
    },
    initialize(){
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.service = Radio.channel('stat');
        this.attributes = this.service.request('get:attributes', this.model);
    },
    templateContext(){
        // Collect data sent to the template (model attributes are already transmitted)
        return {label: this.service.request('find:label', this.model)};
    },
    onFormSubmit(event){
        event.preventDefault(); 
        document.activeElement.blur(); 
    },
    onActionClicked(action_name){
        /*
        * add click on ouvre une popup pour sélectionner le champ à traiter
        * on met le parent_id en mémoire dans un coin 
        */
       console.log("CommonCriteriaView.onActionClicked '%s'", action_name)
        if (action_name == 'add'){
            this.triggerMethod('add:click', this.model);
        } else if (action_name == 'delete'){
            this.triggerMethod('criterion:delete', this.model);
        }
    },
    onModelSaved(field){},
    showSelector(){
        /* 
        Show the selector for the field name
        */
        const view = new SelectWidget({
            title: "Champ",
            options: this.attributes,
            id_key: 'name',
            value: this.model.get('key'),
            field_name: 'key'
       })
       this.showChildView('selector', view)
    },
    showMethod(){
        /* 
        Show the selector for the filter method
        */
       console.log("showMethod");
       console.log(this.model);
        const methods = this.service.request('find:methods', this.model.get('type'));

        let add_default = false;
        if (! this.model.get('method')){
            add_default = true;
        }

        const view = new SelectWidget({
            title: "Filtre",
            options: methods,
            value: this.model.get('method'),
            field_name: 'method',
            placeholder: add_default ? '': undefined,
        })
        this.showChildView('method', view)
    },
    _showStaticOptFields(){
        const options = this.service.request("find:static_options", this.model.get('key'));
        const view = new SelectWidget({
            title: "Valeur",
            value: this.model.get('searches'),
            field_name: 'searches',
            options: options,
            placeholder: '',
            multiple: true,
        })
        this.showChildView('search1', view);
    },
    _showManyToOneFields(){
        const options = this.service.request("find:manytoone_options", this.model.get('key'));
        const view = new SelectWidget({
            title: "Valeur",
            value: this.model.get('searches'),
            field_name: 'searches',
            options: options,
            placeholder: '',
            multiple: true,
        })
        this.showChildView('search1', view);
    },
    _showStringField(){
        const view = new InputWidget({
            title: "Libellé",
            value: this.model.get('search1'),
            field_name: 'search1',
        });
        this.showChildView('search1', view);
    },
    _showNumberField(){
        const method = this.model.get('method');
        let label = "Valeur à comparer"
        if (['bw', 'nbw'].includes(method)){
            label = "Entre"
        }
        const view = new InputWidget({
            title: "",
            ariaLabel: label,
            value: this.model.get('search1'),
            field_name: 'search1',
        });
        this.showChildView('search1', view);
        if (['bw', 'nbw'].includes(method)){
            const view2 = new InputWidget({
                title: "Et",
                value: this.model.get('search2'),
                field_name: 'search2',
            });
            this.showChildView('search2', view2);
        }   
    },
    _showDateField(){
        const method = this.model.get('method');
        if (['dr', 'ndr'].includes(method)){
            let label1 = "Entre le";
            let label2 = "Et le";
            const view1 = new DateWidget({
                title: label1,
                value: this.model.get('date_search1'),
                field_name: "date_search1"
            });
            this.showChildView('search1', view1);
            const view2 = new DateWidget({
                title: label2,
                value: this.model.get('date_search2'),
                field_name: "date_search2"
            });
            this.showChildView('search2', view2);
        }
    },
    showSearches(){
        /*
            Show the search fields (date range, option selection)
        */
        this.detachChildView('search1');
        this.detachChildView('search2');
        if (!this.model.get('method') || ['nll', 'nnll'].includes(this.model.get('method'))){
            return;
        }
        const fieldType = this.model.get('type');
        if (fieldType == 'static_opt'){
            this._showStaticOptFields();
        } else if (fieldType == 'manytoone'){
            this._showManyToOneFields();
        } else if (fieldType == 'string'){
            this._showStringField();
        } else if (fieldType == 'number'){
            this._showNumberField();
        } else if (fieldType == 'date') {
            this._showDateField();
        }
        // field_type + method -> show field
    },
    onFieldSelect(field_name, field_value){
        if (this.model.get(field_name) == field_value){
            return;
        }
        const new_vals = {}
        new_vals[field_name] = field_value;
        let callback;
        if (field_name == 'key'){
            const field = this.attributes[field_value];
            new_vals['type'] = field['type'];
            callback = () => {this.showMethod(); this.showFields();}
        } else if (field_name == 'method'){
            callback = () => {this.showFields();}
        }
        this.model.save(new_vals, {wait: true, patch: true, success: callback});
    },
    showFields(){
        this.showSelector();
        this.showMethod();
        this.showSearches();
    },
    showButtons(){
        /*
         * Show Delete and optionnal Add button 
        */
        const model = new ButtonModel(
            {
                label: "Supprimer", 
                showLabel: false, 
                action: 'delete',
                icon: 'trash-alt'
            }
        );
        const button = new ButtonWidget({model: model, surroundingTagName: 'div', surroundingCss: 'actions'});
        this.showChildView("deleteButton", button);

        // On affiche le bouton d'ajout que si le parent n'est pas une relation onetomany et si le parent a plusieurs enfants
        if (this.model.collection.path == 0 && this.model.collection.length > 1){
            const model = new ButtonModel({
                label: "Ajouter un critère à ce niveau de la hiérarchie", 
                showLabel: false, 
                icon: 'plus', 
                action: 'add'
            });
            const button = new ButtonWidget({model: model, surroundingTagName: 'div', surroundingCss: 'actions'});
            this.showChildView("addButton", button)
        } else {
            this.$el.find('ul').hide();
        }
    },
    showCombination(){
        // Affichage du toggle ET/OU
        if ((this.model.collection.indexOf(this.model) >= 1) && (this.model.collection.path.length == 0)) {
            const view = new CombinationView({model:this.model.collection._parent});
            this.showChildView('combination', view)
        }
    },
    onRender(){
        this.showButtons();

        this.showCombination();
        this.showFields();
    },
});
export default CommonCriteriaView;
